<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.dictName" clearable class="filter-item" style="width: 200px;" placeholder="请输入字典名称"/>
      <el-button v-permission="['GET /admin/dicts']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/dicts']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreateDict">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="字典编码" prop="dictCode" sortable/>
      <el-table-column align="center" label="字典名称" prop="dictName" sortable/>

      <el-table-column align="center" label="说明" prop="description"/>

      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['PUT /admin/dicts/{dictId}']" type="primary" size="mini" @click="handleUpdateDict(scope.row)">编辑</el-button>
          <el-button v-permission="['DELETE /admin/dicts/{dictId}']" type="danger" size="mini" @click="handleDeleteDict(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dictFormStatus]" :visible.sync="dictFormVisible">
      <el-form ref="dictForm" :rules="dictRules" :model="dictForm" status-icon label-position="left" label-width="100px">
        <el-form-item label="字典编码" prop="dictCode">
          <el-input v-model="dictForm.dictCode"/>
        </el-form-item>
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="dictForm.dictName"/>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="dictForm.description"/>
        </el-form-item>


        <el-table v-loading="itemsLoading" :data="items" element-loading-text="正在查询中。。。" border fit highlight-current-row>
          <el-table-column align="center" label="字典项名" prop="itemText" sortable/>
          <el-table-column align="center" label="字典项值" prop="itemValue" sortable/>

          <el-table-column align="center" label="说明" prop="description"/>

          <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-permission="['PUT /admin/dicts/{dictId}/items']" type="primary" size="mini" @click="handleUpdateDictItem(scope.row)">编辑</el-button>
              <el-button v-permission="['DELETE /admin/dicts/{dictId}/items/{dictItemId}']" type="danger" size="mini" @click="handleDeleteDictItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dictFormVisible = false">取消</el-button>
        <el-button v-if="dictFormStatus!='create'" type="primary" @click="handleCreateDictItem">添加字典项</el-button>
        <el-button v-if="dictFormStatus=='create'" type="primary" @click="createDict">确定</el-button>
        <el-button v-else type="primary" @click="updateDict">确定</el-button>
      </div>
    </el-dialog>

    <!-- 字典项配置对话框 -->
    <el-dialog :title="textMap[dictItemFormStatus]" :visible.sync="dictItemDialogFormVisible">
      <el-form ref="dictItemForm" :rules="dictItemRules" :model="dictItemForm" status-icon label-position="left" label-width="100px" >
        <el-form-item label="字典项名称" prop="itemText">
          <el-input v-model="dictItemForm.itemText"/>
        </el-form-item>
        <el-form-item label="字典项值" prop="itemValue">
          <el-input v-model="dictItemForm.itemValue"/>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="dictItemForm.description"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dictItemDialogFormVisible = false">取消</el-button>
        <el-button v-if="dictItemFormStatus=='create'" type="primary" @click="createDictItem">确定</el-button>
        <el-button v-else type="primary" @click="updateDataItem">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listDict, createDict, updateDict, deleteDict, listDictItem, createDictItem, updateDictItem, deleteDictItem } from '@/api/dict'
export default {
  name: 'Dict',
  data() {
    return {
      list: null,
      items: null,
      listLoading: true,
      itemsLoading: false,
      listQuery: {
        dictName: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dictForm: {
        id: undefined,
        dictCode: undefined,
        dictName: undefined,
        description: undefined
      },
      dictItemForm:{
        dictId: undefined,
        id: undefined,
        itemText: undefined,
        itemValue: undefined,
        description: undefined
      },
      dictFormVisible: false,
      dictFormStatus: '',
      dictItemDialogFormVisible: false,
      dictItemFormStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dictRules: {
          dictCode: [{ required: true, message: '字典编码不能为空', trigger: 'blur' }],
          dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
      },
      dictItemRules: {
          itemValue: [{ required: true, message: '字典项值不能为空', trigger: 'blur' }],
          itemText: [{ required: true, message: '字典项名称不能为空', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listDict(this.listQuery)
        .then(response => {
          this.list = response.data.data
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.listLoading = false
        })
    },
    handleFilter() {
      this.getList()
    },
    resetForm() {
      this.dictForm ={
        id: undefined,
        dictCode: undefined,
        dictName: undefined,
        desc: undefined
      }
    },
    handleCreateDict() {
      this.resetForm()
      this.dictFormStatus = 'create'
      this.dictFormVisible = true
      this.$nextTick(() => {
        this.$refs['dictForm'].clearValidate()
      })
    },
    createDict() {
      this.$refs['dictForm'].validate(valid => {
        if (valid) {
          createDict(this.dictForm)
            .then(response => {
              this.getList()
              this.dictFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加字典成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdateDict(row) {
      this.dictForm = Object.assign({}, row)
      this.dictDialogStatus = 'update'
      this.dictFormVisible = true
      this.dictItemForm.dictId= row.id

      this.getDictItems(row.id);

      this.$nextTick(() => {
        this.$refs['dictForm'].clearValidate()
      })
    },
    updateDict() {
      this.$refs['dictForm'].validate(valid => {
        if (valid) {
          updateDict(this.dictForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dictForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dictForm)
                  break
                }
              }
              this.dictFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新字典成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDeleteDict(row) {
      deleteDict(row.id)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除字典成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleCreateDictItem() {
      this.dictItemDialogFormVisible = true;
      this.dictItemFormStatus = "create";
    },
    createDictItem() {
      this.itemsLoading = true;
      createDictItem(this.dictItemForm).then(res=>{
        this.$notify.success({
            title: '成功',
            message: '添加成功'
        });
        this.getDictItems(this.dictItemForm.dictId);
        this.dictItemDialogFormVisible = false;
        this.dictItemForm = {
          dictId: this.dictItemForm.dictId,
          itemText: undefined,
          itemValue: undefined,
          description: undefined
        }
      }).finally(()=>{
        this.itemsLoading = false;
      });
    },
    handleUpdateDictItem(row){
      this.dictItemDialogFormVisible = true;
      this.dictFormStatus = "update";
      this.dictItemFormStatus = "update";
      this.dictItemForm.id = row.id;
      this.dictItemForm.itemText = row.itemText;
      this.dictItemForm.itemValue = row.itemValue;
      this.dictItemForm.description = row.description;
    },
    updateDataItem() {
      this.itemsLoading = true;
      updateDictItem(this.dictItemForm).then(res=>{
        this.$notify.success({
            title: '成功',
            message: '添加成功'
        });
        this.getDictItems(this.dictItemForm.dictId);
        this.dictItemDialogFormVisible = false;
        this.dictItemForm = {
          dictId: this.dictItemForm.dictId,
          id: undefined,
          itemText: undefined,
          itemValue: undefined,
          description: undefined
        }
      }).finally(()=>{
        this.itemsLoading = false;
      });
    },
    handleDeleteDictItem(row){
      this.itemsLoading = true;
      deleteDictItem(this.dictItemForm.dictId, row.id).then(res=>{
        this.$notify.success({
            title: '成功',
            message: '添加成功'
        });
        this.getDictItems(this.dictItemForm.dictId);
      }).finally(()=>{
        this.itemsLoading = false;
      });
    },
    getDictItems(dictId){
      this.itemsLoading = true;
      listDictItem(dictId).then(res => {
          this.items = res.data.data;
      }).finally(()=>{
          this.itemsLoading = false;
      });
    }

  }
}
</script>
